#!/usr/bin/env bash

if [ $# -lt 2 ]; then
   echo "please input : cache_id  data_date"
   exit
fi

cache_id=$1
data_date=$2

tmp_file=/tmp/cache_id_$cache_id.sql

cat >> $tmp_file << EOF

add jar $HADOOP_HOME/jars/Acrm.jar;
create temporary function acrmR as 'demo.yalatin.AcrmR';
create temporary function acrmF as 'demo.yalatin.AcrmF';
create temporary function acrmM1 as 'demo.yalatin.AcrmM1';
create temporary function acrmM2 as 'demo.yalatin.AcrmM2';
create temporary function acrmM as 'demo.yalatin.AcrmM';

INSERT OVERWRITE TABLE acrm_rfm
 select '$cache_id',b.customer_id, b.R,b.F,c.M, round(b.R*0.45+b.F*0.35+c.M*0.20,2) as RFM 
		from (  select a.customer_id, acrmR(to_date('$data_date'),a.tran_date) as R , acrmF(freq)  as F 
			          from (select customer_id,max(tran_date)  as tran_date,count(1) as freq from acrm_transaction group by customer_id) a) b 
			     join
 				 (  select customer_id, acrmM(sum(acrmM1(tran_type)*acrmM2(amount))) as M from acrm_transaction group by customer_id) c 
		  on b.customer_id = c.customer_id;
EOF

$HIVE_HOME/bin/hive -f "$tmp_file"

rm $tmp_file


